package com.llu.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component  // 需要注册为Bean
public class TestFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 先获取 ServerHttpRequest 对象，注意不是 HttpServletRequest
        ServerHttpRequest request = exchange.getRequest();
        // 打印一下所有的请求参数
        log.info("请求参数: " + request.getQueryParams());
        // 判断是否包含 val 参数，且参数值为 1
        List<String> value = request.getQueryParams().get("val");
        if(value != null && value.contains("1")) {
            // 将 ServerWebExchange 向过滤链的下一级传递（跟 JavaWeb 中介绍的过滤器其实是差不多的）
            return chain.filter(exchange);
        }else {
            // 直接在这里拦截，然后返回响应
            return exchange.getResponse().setComplete();
        }
    }
}
